import { Card, Empty, Select } from 'antd';
import { FC } from 'react';

import { ApiResponse, get, post } from '@/api';
import { NODE_TYPE } from '@/constants/config';
import { useCurrentNode } from '@/hooks/useCurrentNode';

import { ResponseVariablesTable } from '../../ResponseVariablesTable';
import { VariablesTable } from '../../VariablesTable';

export const ApiConfig: FC = memo(() => {
  const [value, setValue] = useState<any>(null);
  const [options, setOptions] = useState<{ value: number; label: string }[]>([]);
  const { getNodeDataFor, setNodeDataFor, setPublicVariables } = useCurrentNode<NODE_TYPE.API>();

  const [requestVariables, setRequestVariables] = useState<Required<ApiResponse<'get', '/api/get'>>['reqVariables']>([]);
  const [responseVariables, setResponseVariables] = useState<Required<ApiResponse<'get', '/api/get'>>['respVariables']>([]);

  // const getModelResponse = async (id: string) => {
  //   let variables: IGetModelGetRes['variables'] = [];
  //   const res = await getModelGet({ id });
  //   variables = res.variables || [];
  //   currentNode.saveCurrentPrivateNodeVariables(variables);
  // };

  const getModelDetails = (id?: number) => {
    if (!id) return;
    get('/api/get', { id }).then((res) => {
      setValue(res.id);
      setRequestVariables(res.reqVariables || []);
      setResponseVariables(res.respVariables || []);
      setPublicVariables(res.respVariables || []);
    });
  };

  useEffect(() => {
    post('/api/enabled/page').then((res) => {
      setOptions(
        res.list?.map((item) => {
          return {
            value: item.id!,
            label: item.apiName!
          };
        }) || []
      );
    });
    const nodeData = getNodeDataFor();
    getModelDetails(nodeData?.actionId);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <Card size="small" title="加载设置">
      <Select
        className="w-full"
        value={value}
        placeholder="请选择API"
        allowClear
        options={options}
        onClear={() => {
          setNodeDataFor({});
          setValue('');
          setRequestVariables([]);
          setResponseVariables([]);
          setPublicVariables([]);
        }}
        onChange={(val) => {
          setNodeDataFor({
            actionId: val
          });
          getModelDetails(val);
        }}
      />
      {requestVariables.length > 0 && <VariablesTable className="py-16" title="模型入参" dataSource={requestVariables} />}
      {responseVariables.length > 0 && (
        <ResponseVariablesTable className="mb-20 py-16" title="模型返回字段" dataSource={responseVariables} />
      )}
      {requestVariables.length <= 0 && responseVariables.length <= 0 && (
        <div className="custom-empty my-24">
          <Empty />
        </div>
      )}
    </Card>
  );
});
